package cn.wolfcode.wolf2w.service.impl;


import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.StrategyCatalog;
import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.query.DestinationQuery;
import cn.wolfcode.wolf2w.query.StrategyCatalogQuery;
import cn.wolfcode.wolf2w.repository.StrategyCatalogRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.IStrategyCatalogService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.vo.CatalogVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class StrategyCatalogServiceImpl implements IStrategyCatalogService {
    @Autowired
    private StrategyCatalogRepository strategyCatalogRepository;
    @Autowired
    private MongoTemplate template;
    @Autowired
    private IDestinationService destinationService;
    @Autowired
    private IStrategyService strategyService;

    @Override
    public void insert(StrategyCatalog strategyCatalog) {
        Destination destination = destinationService.selectOne(strategyCatalog.getDestId());
        strategyCatalog.setDestName(destination.getName());
        strategyCatalog.setId(null);
        strategyCatalogRepository.save(strategyCatalog);
    }

    @Override
    public void delete(String id) {
        strategyCatalogRepository.deleteById(id);
    }

    @Override
    public void update(StrategyCatalog strategyCatalog) {
        Destination destination = destinationService.selectOne(strategyCatalog.getDestId());
        strategyCatalog.setDestName(destination.getName());
        strategyCatalogRepository.save(strategyCatalog);
    }

    @Override
    public StrategyCatalog findById(String id) {
        Optional<StrategyCatalog> strategyCatalog = strategyCatalogRepository.findById(id);
        return strategyCatalog.orElse(null);
    }

    @Override
    public List<StrategyCatalog> findAll() {
        List<StrategyCatalog> all = strategyCatalogRepository.findAll();
        return all;
    }

    @Override
    public Page<StrategyCatalog> query(StrategyCatalogQuery qo, String parentId) {
        Query query = new Query();

        if (StringUtils.hasText(parentId)){
            query.addCriteria(Criteria.where("parentId").is(parentId));
        }else {
            query.addCriteria(Criteria.where("parentId").is(null));
        }

        if (StringUtils.hasText(qo.getKeyword())){
            query.addCriteria(Criteria.where("name").regex(qo.getKeyword()));
        }
        long total = template.count(query, StrategyCatalog.class);
        if (total == 0){
            return Page.empty();
        }
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),Sort.Direction.ASC, "sequence");
        query.with(pageable);
        List<StrategyCatalog> list = template.find(query, StrategyCatalog.class);
        return new PageImpl<>(list, pageable,total);
    }

    @Override
    public void updateStateById(String id) {
        Query query = new Query();
        Update update = new Update();
        update.set("state", 1);
        query.addCriteria(Criteria.where("_id").is(id));
        template.updateMulti(query, update, StrategyCatalog.class);
    }

    @Override
    public List findByState() {
        /*//使用分组查询
        Aggregation articleNo = Aggregation.newAggregation(Aggregation.match(Criteria.where("state").is(0)),
                Aggregation.group("destName").first("destName").as("destName"));

        AggregationResults<StrategyCatalog> aggregate = template.aggregate(articleNo, "strategy_catalog", StrategyCatalog.class);
        List<StrategyCatalog> catalog = aggregate.getMappedResults();


        for (StrategyCatalog strategyCatalog : catalog) {
            strategyCatalog.setMapList(strategyCatalogRepository.findByDestName(strategyCatalog.getDestName()));
        }
        return catalog;*/

        Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(Criteria.where("state").is(0)),
                Aggregation.group("destName")
                        .push("name").as("names")
                        .push("_id").as("ids"));

        AggregationResults<Map> aggregate = template.aggregate(aggregation,"strategy_catalog", Map.class);

        List<Map> catalogs = aggregate.getMappedResults();

        ArrayList<CatalogVo> catalogVos = new ArrayList<>();

        for (Map catalog : catalogs) {
            CatalogVo catalogVo = new CatalogVo();
            ArrayList<StrategyCatalog> strategyCatalogs = new ArrayList<>();
            catalogVo.setDestName(catalog.get("_id").toString());
            List names = (List<Object>) catalog.get("names");
            List ids = (List<Object>) catalog.get("ids");
            for (int i = 0 ; i < names.size();i++){
                StrategyCatalog strategyCatalog = new StrategyCatalog();
                strategyCatalog.setName(names.get(i).toString());
                strategyCatalog.setId(ids.get(i).toString());
                strategyCatalogs.add(strategyCatalog);
            }
            catalogVo.setMapList(strategyCatalogs);
            catalogVos.add(catalogVo);
        }
        return catalogVos;
    }

    @Override
    public List<StrategyCatalog> findByDestId(String destId) {
        System.out.println(destId);
        List<StrategyCatalog> strategyCatalogs = strategyCatalogRepository.findByDestId(destId);
        System.out.println(strategyCatalogs);
        return strategyCatalogs;
    }


}
